var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/heimweghelden');

function keycheck(key) {
	key = "";
	key = key.trim();
	var success =
		key.substr(0, 30) === '-----BEGIN RSA PUBLIC KEY-----' &&
		key.substr(key.length-28) === '-----END RSA PUBLIC KEY-----';
	return success;
}
exports.register = function(data, listener) {
	if
	(
		typeof data.key === 'undefined' ||
		data.key === null ||
		typeof data.phone === 'undefined' ||
		data.phone === null ||
		!keycheck(data.key) ||
		data.phone.trim() === ''
	)
    {
        listener({success:false, data: null, message: 'invalid request'});
    }

	var value = {
		'_id': data.phone.trim(),
		'key': data.key.trim()
	};
	var collection = db.get('user');
	//TODO: check of exist, if exist, notify user and overwrite
	collection.insert(value, function (err, doc) {
		listener({success:!(err), data: err });
	});
};

exports.fetchcerts = function(data, listener) {
	if (
		typeof data.numbers === 'undefined' ||
		data.numbers.length < 1
	) {
		listener({success:false, data: null, message: 'no numbers given'});
	}
	var numbers = [];
	data.numbers.forEach(function(number) {
		numbers.push(number);
	});
	db.get('user').find({_id:{$in:numbers}}, function(err, doc) {
		listener({success:!(err), data: doc});
	});
};